<template>
  <div class="profile">
    <div class="container">
      <!-- Profile Header -->
      <div class="profile-header">
        <div class="profile-avatar-wrapper">
          <div class="profile-avatar" :class="{ admin: isAdmin }">
            <img v-if="authStore.userAvatar && authStore.userAvatar !== '/default-avatar.png'" 
                 :src="authStore.userAvatar" 
                 alt="用户头像" 
                 class="avatar-img" />
            <Crown v-else-if="isAdmin" :size="48" />
            <Users v-else :size="48" />
          </div>
          <button @click="showEditModal = true" class="avatar-edit-btn" title="更换头像">
            <Camera :size="16" />
          </button>
        </div>
        <div class="profile-info">
          <h2 class="profile-name">
            {{ authStore.currentUser?.name || '游客' }}
            <span v-if="isAdmin" class="admin-badge">管理员</span>
          </h2>
          <p class="profile-email">{{ authStore.currentUser?.email || 'user@example.com' }}</p>
          <div class="profile-stats">
            <div class="stat">
              <span class="stat-number">{{ userStories.length }}</span>
              <span class="stat-label">故事</span>
            </div>
            <div class="stat">
              <span class="stat-number">{{ totalLikes }}</span>
              <span class="stat-label">获赞</span>
            </div>
            <div class="stat">
              <span class="stat-number">{{ totalViews }}</span>
              <span class="stat-label">阅读</span>
            </div>
          </div>
        </div>
        <div class="profile-actions">
          <button @click="showEditModal = true" class="btn btn-outline">
            <Edit3 :size="16" />
            编辑资料
          </button>
        </div>
      </div>

      <!-- Profile Tabs -->
      <div class="profile-tabs">
        <button
          v-for="tab in profileTabs"
          :key="tab.key"
          @click="activeTab = tab.key"
          :class="{ active: activeTab === tab.key }"
          class="profile-tab"
        >
          <component :is="tab.icon" :size="18" />
          <span>{{ tab.label }}</span>
        </button>
      </div>

      <!-- Tab Content -->
      <div class="tab-content">
        <!-- My Stories -->
        <div v-if="activeTab === 'stories'" class="stories-section">
          <div class="section-header">
            <h2>我的故事</h2>
          </div>
          
          <div v-if="userStories.length === 0" class="empty-state">
            <BookOpen :size="48" />
            <h3>还没有故事</h3>
            <p>开始创作你的第一个故事吧！</p>
            <router-link to="/generate" class="btn btn-primary">
              <Edit :size="16" />
              开始创作
            </router-link>
          </div>
          
          <div v-else class="stories-grid">
            <div
              v-for="story in userStories"
              :key="story.id"
              class="story-card card"
              @click="goToStory(story.id)"
            >
              <div class="story-header">
                <div class="story-status">
                  <span class="story-category">{{ story.category }}</span>
                  <span 
                    class="status-badge" 
                    :class="story.status"
                  >
                    {{ story.status === 'published' ? '已发布' : '草稿' }}
                  </span>
                </div>
                <div class="story-actions">
                  <button v-if="story.status === 'draft'" @click.stop="publishStory(story.id)" class="action-btn publish">
                    <Send :size="14" />
                  </button>
                  <button @click.stop="editStory(story)" class="action-btn">
                    <Edit :size="14" />
                  </button>
                  <button @click.stop="deleteStory(story.id)" class="action-btn delete">
                    <Trash2 :size="14" />
                  </button>
                </div>
              </div>
              
              <h3 class="story-title">{{ story.title }}</h3>
              <p class="story-excerpt">{{ getExcerpt(story.content) }}</p>
              
              <div class="story-meta">
                <div class="story-stats">
                  <span class="stat">
                    <Eye :size="14" />
                    {{ story.views || 0 }}
                  </span>
                  <span class="stat">
                    <Heart :size="14" />
                    {{ story.likes || 0 }}
                  </span>
                  <span class="stat">
                    <MessageCircle :size="14" />
                    {{ story.comments?.length || 0 }}
                  </span>
                </div>
                <span class="story-date">{{ formatDate(story.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Liked Stories -->
        <div v-if="activeTab === 'liked'" class="stories-section">
          <div class="section-header">
            <h2>点赞的故事</h2>
          </div>
          
          <div v-if="likedStories.length === 0" class="empty-state">
            <Heart :size="48" />
            <h3>还没有点赞的故事</h3>
            <p>去发现喜欢的故事并点赞吧！</p>
            <router-link to="/" class="btn btn-primary">
              <BookOpen :size="16" />
              浏览故事
            </router-link>
          </div>
          
          <div v-else class="stories-grid">
            <div
              v-for="story in likedStories"
              :key="story.id"
              class="story-card card"
              @click="goToStory(story.id)"
            >
              <div class="story-header">
                <div class="story-status">
                  <span class="story-category">{{ story.category }}</span>
                </div>
              </div>
              
              <h3 class="story-title">{{ story.title }}</h3>
              <p class="story-excerpt">{{ getExcerpt(story.content) }}</p>
              
              <div class="story-meta">
                <div class="story-stats">
                  <span class="stat">
                    <Eye :size="14" />
                    {{ story.views || 0 }}
                  </span>
                  <span class="stat">
                    <Heart :size="14" />
                    {{ story.likes || 0 }}
                  </span>
                  <span class="stat">
                    <MessageCircle :size="14" />
                    {{ story.comments_count || 0 }}
                  </span>
                </div>
                <span class="story-author">作者: {{ story.author_name }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Bookmarked Stories -->
        <div v-if="activeTab === 'bookmarked'" class="stories-section">
          <div class="section-header">
            <h2>收藏的故事</h2>
          </div>
          
          <div v-if="bookmarkedStories.length === 0" class="empty-state">
            <Bookmark :size="48" />
            <h3>还没有收藏的故事</h3>
            <p>收藏喜欢的故事，方便以后阅读！</p>
            <router-link to="/" class="btn btn-primary">
              <BookOpen :size="16" />
              浏览故事
            </router-link>
          </div>
          
          <div v-else class="stories-grid">
            <div
              v-for="story in bookmarkedStories"
              :key="story.id"
              class="story-card card"
              @click="goToStory(story.id)"
            >
              <div class="story-header">
                <div class="story-status">
                  <span class="story-category">{{ story.category }}</span>
                </div>
              </div>
              
              <h3 class="story-title">{{ story.title }}</h3>
              <p class="story-excerpt">{{ getExcerpt(story.content) }}</p>
              
              <div class="story-meta">
                <div class="story-stats">
                  <span class="stat">
                    <Eye :size="14" />
                    {{ story.views || 0 }}
                  </span>
                  <span class="stat">
                    <Heart :size="14" />
                    {{ story.likes || 0 }}
                  </span>
                  <span class="stat">
                    <MessageCircle :size="14" />
                    {{ story.comments_count || 0 }}
                  </span>
                </div>
                <span class="story-author">作者: {{ story.author_name }}</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- Edit Profile Modal -->
    <div v-if="showEditModal" class="modal-overlay" @click="showEditModal = false">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>编辑个人资料</h2>
          <button @click="showEditModal = false" class="close-btn">
            <X :size="20" />
          </button>
        </div>
        
        <div class="modal-body">
          <!-- 头像上传 -->
          <div class="form-group">
            <label>头像</label>
            <div class="avatar-upload">
              <div class="avatar-preview" :class="{ admin: isAdmin }">
                <img v-if="previewAvatar" :src="previewAvatar" alt="头像预览" />
                <Users v-else :size="48" />
              </div>
              <div class="upload-actions">
                <input 
                  ref="fileInput" 
                  type="file" 
                  accept="image/*" 
                  @change="handleFileChange" 
                  style="display: none"
                />
                <button @click="$refs.fileInput.click()" type="button" class="btn btn-secondary">
                  <Camera :size="16" />
                  选择图片
                </button>
                <button v-if="previewAvatar" @click="removeAvatar" type="button" class="btn btn-outline">
                  移除
                </button>
              </div>
              <p class="hint">支持 JPG、PNG，最大 5MB</p>
            </div>
          </div>
          
          <div class="form-group">
            <label>用户名</label>
            <input v-model="editForm.username" type="text" class="form-input" />
          </div>
          
          <div class="form-group">
            <label>个人简介</label>
            <textarea v-model="editForm.bio" class="form-textarea" rows="4"></textarea>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="showEditModal = false" class="btn btn-secondary">取消</button>
          <button @click="saveProfile" class="btn btn-primary">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useStoriesStore } from '../stores/stories'
import { useToast } from 'vue-toastification'
import { gsap } from 'gsap'
import {
  BookOpen,
  Edit,
  Edit3,
  Trash2,
  Send,
  Eye,
  Heart,
  MessageCircle,
  Crown,
  Users,
  Camera,
  Bookmark,
  ThumbsUp
} from 'lucide-vue-next'

const router = useRouter()
const authStore = useAuthStore()
const storiesStore = useStoriesStore()
const toast = useToast()

const activeTab = ref('stories')
const showEditModal = ref(false)
const showAvatarModal = ref(false)
const storyFilter = ref('all')
const fileInput = ref(null)
const avatarFile = ref(null)
const previewAvatar = ref('')

const editForm = ref({
  username: '',
  bio: ''
})

const profileTabs = ref([
  { key: 'stories', label: '我的故事', icon: BookOpen },
  { key: 'liked', label: '点赞的故事', icon: Heart },
  { key: 'bookmarked', label: '收藏的故事', icon: Bookmark }
])

const user = computed(() => authStore.user)

const isAdmin = computed(() => {
  return authStore.currentUser?.role === 'admin'
})

const userStories = computed(() => {
  if (!authStore.currentUser) return []
  // 支持多种字段名格式：author_id (后端) 和 authorId (前端)
  return storiesStore.stories.filter(story => 
    story.author_id === authStore.currentUser.id || 
    story.authorId === authStore.currentUser.id
  )
})

const likedStories = computed(() => {
  if (!authStore.currentUser) return []
  // 获取用户点赞的故事
  return storiesStore.stories.filter(story => story.is_liked === true)
})

const bookmarkedStories = computed(() => {
  if (!authStore.currentUser) return []
  // 获取用户收藏的故事（假设后端有is_bookmarked字段）
  return storiesStore.stories.filter(story => story.is_bookmarked === true)
})

const publishedUserStories = computed(() => {
  return userStories.value.filter(story => story.status === 'published')
})

const draftUserStories = computed(() => {
  return userStories.value.filter(story => story.status === 'draft')
})

const filteredUserStories = computed(() => {
  switch (storyFilter.value) {
    case 'published':
      return publishedUserStories.value
    case 'draft':
      return draftUserStories.value
    default:
      return userStories.value
  }
})

const totalLikes = computed(() => {
  return userStories.value.reduce((sum, story) => sum + story.likes, 0)
})

const totalViews = computed(() => {
  return userStories.value.reduce((sum, story) => sum + story.views, 0)
})

const userAchievements = computed(() => [
  {
    id: 1,
    title: '初出茅庐',
    description: '发布第一个故事',
    icon: BookOpen,
    progress: userStories.value.length > 0 ? 100 : 0,
    unlocked: userStories.value.length > 0
  },
  {
    id: 2,
    title: '人气作家',
    description: '获得100个点赞',
    icon: Heart,
    progress: Math.min((totalLikes.value / 100) * 100, 100),
    unlocked: totalLikes.value >= 100
  },
  {
    id: 3,
    title: '多产作家',
    description: '发布10个故事',
    icon: Award,
    progress: Math.min((userStories.value.length / 10) * 100, 100),
    unlocked: userStories.value.length >= 10
  }
])

const getExcerpt = (content) => {
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const goToStory = (storyId) => {
  router.push(`/story/${storyId}`)
}

const goToPage = (path) => {
  router.push(path)
}

const editStory = (story) => {
  router.push(`/generator?edit=${story.id}`)
}

const publishStory = async (storyId) => {
  try {
    await storiesStore.publishStory(storyId)
    toast.success('故事发布成功！')
  } catch (error) {
    toast.error('发布失败：' + (error.message || '请重试'))
  }
}

const deleteStory = async (storyId) => {
  if (confirm('确定要删除这个故事吗？')) {
    try {
      await storiesStore.deleteStory(storyId)
    } catch (error) {
      toast.error('删除失败：' + (error.message || '请重试'))
    }
  }
}

const getEmptyMessage = () => {
  switch (storyFilter.value) {
    case 'published':
      return '还没有发布的故事'
    case 'draft':
      return '还没有草稿'
    default:
      return '还没有创作故事'
  }
}

const getEmptyDescription = () => {
  switch (storyFilter.value) {
    case 'published':
      return '发布您的第一个故事，与大家分享您的创意'
    case 'draft':
      return '开始创作您的第一个故事草稿'
    default:
      return '开始您的创作之旅，用AI生成精彩的故事'
  }
}

// 头像上传处理
const handleFileChange = (event) => {
  const file = event.target.files?.[0]
  if (!file) return
  
  if (!file.type.startsWith('image/')) {
    toast.error('请选择图片文件')
    return
  }
  
  if (file.size > 5 * 1024 * 1024) {
    toast.error('图片大小不能超过5MB')
    return
  }
  
  avatarFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const removeAvatar = () => {
  avatarFile.value = null
  previewAvatar.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const saveProfile = async () => {
  try {
    console.log('=== 开始保存个人资料 ===')
    const formData = new FormData()
    
    if (editForm.value.username) {
      formData.append('name', editForm.value.username)
      console.log('添加用户名:', editForm.value.username)
    }
    if (editForm.value.bio) {
      formData.append('bio', editForm.value.bio)
      console.log('添加个人简介:', editForm.value.bio)
    }
    if (avatarFile.value) {
      formData.append('avatar', avatarFile.value)
      console.log('添加头像文件:', avatarFile.value.name, avatarFile.value.size, 'bytes')
    }
    
    // 打印FormData内容（调试用）
    console.log('FormData内容:')
    for (let pair of formData.entries()) {
      console.log(pair[0], ':', pair[1])
    }
    
    // 更新用户资料
    console.log('调用authStore.updateProfile...')
    await authStore.updateProfile(formData)
    
    // 清空预览和文件
    avatarFile.value = null
    previewAvatar.value = ''
    if (fileInput.value) {
      fileInput.value.value = ''
    }
    
    showEditModal.value = false
    toast.success('个人资料更新成功！')
    console.log('=== 个人资料保存成功 ===')
  } catch (error) {
    console.error('=== 保存个人资料失败 ===')
    console.error('错误:', error)
    toast.error('更新失败：' + (error.message || '请重试'))
  }
}

// 监听编辑弹窗打开，初始化表单数据
watch(showEditModal, (newValue) => {
  if (newValue && authStore.currentUser) {
    // 打开弹窗时，从当前用户数据初始化表单
    editForm.value.username = authStore.currentUser.name || ''
    editForm.value.bio = authStore.currentUser.bio || ''
    
    // 初始化头像预览
    if (authStore.userAvatar && authStore.userAvatar !== '/default-avatar.png') {
      previewAvatar.value = authStore.userAvatar
    } else {
      previewAvatar.value = ''
    }
    
    console.log('初始化编辑表单:', editForm.value)
    console.log('初始化头像预览:', previewAvatar.value)
  }
})

onMounted(async () => {
  // 加载用户的故事数据
  try {
    if (authStore.currentUser) {
      console.log('加载用户故事，用户ID:', authStore.currentUser.id)
      await storiesStore.loadStories({
        author_id: authStore.currentUser.id,
        page: 1,
        page_size: 100
      })
      console.log('用户故事加载完成，总数:', storiesStore.stories.length)
      console.log('当前用户的故事数:', userStories.value.length)
    }
  } catch (error) {
    console.error('加载用户故事失败:', error)
    toast.error('加载故事列表失败')
  }
  
  editForm.value = {
    username: authStore.currentUser?.name || '',
    bio: authStore.currentUser?.bio || ''
  }
  
  // 初始化头像预览
  if (authStore.userAvatar && authStore.userAvatar !== '/default-avatar.png') {
    previewAvatar.value = authStore.userAvatar
  }
  
  // 延迟动画，确保DOM已更新
  setTimeout(() => {
    const cards = document.querySelectorAll('.story-card')
    if (cards.length > 0) {
      gsap.fromTo('.story-card',
        { opacity: 0, y: 30 },
        {
          opacity: 1,
          y: 0,
          duration: 0.6,
          stagger: 0.1,
          ease: 'power2.out'
        }
      )
    }
  }, 100)
})
</script>

<style scoped>
.profile {
  padding: var(--spacing-2xl) 0;
  min-height: 100vh;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-2xl);
  margin-bottom: var(--spacing-3xl);
  padding: var(--spacing-2xl);
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  border: 1px solid var(--border-color);
}

.profile-avatar-wrapper {
  position: relative;
}

.profile-avatar {
  width: 120px;
  height: 120px;
  background: var(--gradient-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  overflow: hidden;
  border: 4px solid var(--bg-secondary);
  transition: all var(--transition-normal);
}

/* 管理员头像特殊样式 */
.profile-avatar.admin {
  border-color: #8b5cf6;
  box-shadow: 0 0 30px rgba(139, 92, 246, 0.5), 0 0 60px rgba(139, 92, 246, 0.3);
  animation: adminGlow 3s ease-in-out infinite;
}

@keyframes adminGlow {
  0%, 100% {
    box-shadow: 0 0 30px rgba(139, 92, 246, 0.5), 0 0 60px rgba(139, 92, 246, 0.3);
  }
  50% {
    box-shadow: 0 0 40px rgba(139, 92, 246, 0.7), 0 0 80px rgba(139, 92, 246, 0.4);
  }
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-edit-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  background: var(--primary-color);
  border: 3px solid var(--bg-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.avatar-edit-btn:hover {
  background: var(--primary-dark);
  transform: scale(1.1);
}

.profile-info {
  flex: 1;
}

.profile-name {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: var(--font-size-2xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.admin-badge {
  display: inline-flex;
  align-items: center;
  padding: var(--spacing-xs) var(--spacing-sm);
  background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%);
  color: white;
  font-size: var(--font-size-xs);
  border-radius: var(--radius-md);
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3);
}

.profile-email {
  color: var(--text-muted);
  margin: 0 0 var(--spacing-md) 0;
}

.profile-bio {
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-lg) 0;
  line-height: 1.6;
}

.profile-stats {
  display: flex;
  gap: var(--spacing-xl);
}

.stat {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: var(--font-size-xl);
  font-weight: 700;
  color: var(--text-primary);
}

.stat-label {
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.profile-actions {
  display: flex;
  gap: var(--spacing-md);
}

.profile-tabs {
  display: flex;
  justify-content: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-2xl);
  border-bottom: 1px solid var(--border-color);
}

.profile-tab {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-md) var(--spacing-xl);
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-weight: 500;
  border-bottom: 2px solid transparent;
}

.profile-tab.active,
.profile-tab:hover {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.section-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
}

.story-filters {
  display: flex;
  gap: 0.5rem;
}

.filter-btn {
  padding: 0.5rem 1rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-secondary);
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.875rem;
}

.filter-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
}

.filter-btn.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.empty-state {
  text-align: center;
  padding: 3rem 1rem;
  color: var(--text-secondary);
}

.empty-state svg {
  color: var(--text-tertiary);
  margin-bottom: 1rem;
}

.empty-state h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1.25rem;
  color: var(--text-primary);
}

.empty-state p {
  margin: 0 0 1.5rem 0;
  font-size: 0.875rem;
}

.empty-state .btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background: var(--primary-color);
  color: white;
  text-decoration: none;
  border-radius: 0.5rem;
  transition: all 0.3s ease;
}

.empty-state .btn:hover {
  background: var(--primary-dark);
  transform: translateY(-2px);
}

.stories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-top: 1.5rem;
}

.story-card {
  cursor: pointer;
  transition: all var(--transition-normal);
  position: relative;
}

.story-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-xl);
}

.story-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.story-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-badge.published {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.2);
}

.status-badge.draft {
  background: rgba(251, 191, 36, 0.1);
  color: #fbbf24;
  border: 1px solid rgba(251, 191, 36, 0.2);
}

.story-actions {
  display: flex;
  gap: var(--spacing-xs);
  opacity: 0;
  transition: opacity var(--transition-fast);
}

.story-card:hover .story-actions {
  opacity: 1;
}

.action-btn {
  width: 28px;
  height: 28px;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.action-btn:hover {
  background: var(--primary-color);
  color: white;
}

.action-btn.delete:hover {
  background: var(--error-color);
}

.action-btn.publish:hover {
  background: #22c55e;
  color: white;
}

.story-category {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.story-title {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
}

.story-excerpt {
  color: var(--text-secondary);
  line-height: 1.5;
  margin: 0 0 var(--spacing-lg) 0;
}

.story-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.story-stats {
  display: flex;
  gap: var(--spacing-md);
}

.story-stats .stat {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.story-author {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.story-date {
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-xl);
}

.achievement-card {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  opacity: 0.6;
  transition: all var(--transition-normal);
}

.achievement-card.unlocked {
  opacity: 1;
}

.achievement-icon {
  width: 60px;
  height: 60px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-xl);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
}

.achievement-card.unlocked .achievement-icon {
  background: var(--gradient-primary);
  color: white;
}

.achievement-info {
  flex: 1;
}

.achievement-title {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
}

.achievement-description {
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-md) 0;
  font-size: var(--font-size-sm);
}

.achievement-progress {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: var(--bg-tertiary);
  border-radius: var(--radius-sm);
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--gradient-primary);
  transition: width var(--transition-normal);
}

.progress-text {
  font-size: var(--font-size-sm);
  font-weight: 500;
  color: var(--text-primary);
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.modal-header h2 {
  margin: 0;
  color: var(--text-primary);
}

.close-btn {
  width: 32px;
  height: 32px;
  background: none;
  border: none;
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-xl);
  overflow-y: auto;
  flex: 1;
  min-height: 0;
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

/* 头像上传样式 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-md);
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid var(--border-color);
  background: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
  transition: all var(--transition-normal);
}

.avatar-preview.admin {
  border-color: #8b5cf6;
  box-shadow: 0 0 20px rgba(139, 92, 246, 0.4);
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.hint {
  font-size: var(--font-size-xs);
  color: var(--text-muted);
  margin: 0;
  text-align: center;
}

.form-group label {
  display: block;
  margin-bottom: var(--spacing-sm);
  color: var(--text-primary);
  font-weight: 500;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: var(--spacing-md);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  color: var(--text-primary);
  font-family: inherit;
  transition: border-color var(--transition-fast);
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  padding: var(--spacing-xl);
  border-top: 1px solid var(--border-color);
}

/* Mobile Styles */
@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-lg);
  }

  .profile-stats {
    justify-content: center;
  }

  .stories-grid {
    grid-template-columns: 1fr;
  }

  .story-meta {
    flex-direction: column;
    gap: var(--spacing-sm);
    align-items: flex-start;
  }

  .achievements-grid {
    grid-template-columns: 1fr;
  }

  .achievement-card {
    flex-direction: column;
    text-align: center;
  }
}
</style>
